package com.example.book_test.service;

import com.example.book_test.mapper.BookInfoMapper;
import com.example.book_test.enums.BookStatusEnum;
import com.example.book_test.model.BookInfo;
import com.example.book_test.model.PageRequest;
import com.example.book_test.model.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Slf4j
@Service
public class BookService {
    @Autowired
    BookInfoMapper bookInfoMapper;

    public PageResult selectBookInfoByPage(PageRequest pageRequest){
        if (pageRequest == null){
            return null;
        }
        log.info(pageRequest.getCurrentPage() + "");
        List<BookInfo> bookInfos = bookInfoMapper.selectBookInfoByPage(pageRequest.getOffset(), pageRequest.getPageSize());
        if (bookInfos != null && bookInfos.size() > 0){
            for (BookInfo bookInfo: bookInfos){
                //根据status获取状态的定义
                bookInfo.setStatusCN(BookStatusEnum.getNameByCode(bookInfo.getStatus()).getName());
            }
        }

        Integer count = bookInfoMapper.count();

        return new PageResult(bookInfos, count, pageRequest);
    }

    public Integer addBook(BookInfo bookInfo){
        Integer result = 0;
        try{
            result = bookInfoMapper.addBook(bookInfo);
            if (result <= 0){
                log.error("service 层添加图书失败:bookInfo:{}",bookInfo);
            }
        }catch (Exception e){
            log.error("添加图书失败，e:{}",e);
        }

        return result;
    }

    public BookInfo queryBookById(Integer id){
        return bookInfoMapper.queryBookById(id);
    }

    public Integer updateBook(BookInfo bookInfo){
        Integer res = 0;
        try{
            res = bookInfoMapper.updateBook(bookInfo);
        }catch (Exception e){
            log.error("更新图书失败,e:{}", e);
        }

        return res;
    }

    public Integer batchDeleteBook(@RequestParam List<Integer> ids){
        Integer res = null;
        try{
            res = bookInfoMapper.batchDelete(ids);
        }catch (Exception e){
            log.error("批量删除失败, ids:{}", ids);
        }

        return res;
    }
}
